/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.web30.feed;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndPerson;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.field.AbstractField;
import org.apache.james.mime4j.field.address.Mailbox;
import org.apache.james.mime4j.message.BodyFactory;
import org.apache.james.mime4j.message.Message;
import org.web30.bookmark.Bookmark;
import org.web30.util.EncodeDetector;

/**
 *
 * @author xiazy
 */
public class MimeMessageBuilder {

    public static String DEFAULT_ENCODING = "UTF-8";
    
    public MimeMessageBuilder() {
        
    }

    public static Message Bookmark2Mime(Bookmark b){
        try {
            Message msg = new Message();
            msg.setFrom(Mailbox.parse(b.getAuthor()));
            msg.setSubject(b.getTitle());
            msg.getHeader().addField(AbstractField.parse("Content-Type: text/html; charset=UTF-8"));
            msg.getHeader().addField(AbstractField.parse("User-Agent: JSON Client API"));
            String url = (new Formatter()).format("<a href=\"%s\">%s</a><br/>",b.getUrl(),b.getTitle()).toString();
            String content = url+b.getContent();
            BodyFactory factory = new BodyFactory();
            msg.setBody(factory.textBody(MimeMessageBuilder.composeHTML(content),DEFAULT_ENCODING));
            return msg;
        } catch (MimeException ex) {
            Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    public Message Entry2Mime(SyndEntry e){
        {
            FileOutputStream stream = null;
            try {
                if (e == null) {
                    return null;
                }
                String subject = e.getTitle();
                if (subject == null) {
                    return null;
                }
                SyndPerson p = (SyndPerson) (e.getAuthors().get(0));
                if (p == null) {
                    return null;
                }
                Message msg = new Message();
                String from = p.getName();
                if (p.getEmail() != null) {
                    from += " <" + p.getEmail() + ">";
                } else {
                    from += " <guest@web30core.org>";
                }
                msg.setFrom(Mailbox.parse(from));
                msg.setSubject(subject);
                msg.getHeader().addField(AbstractField.parse("Content-Type: text/html; charset=UTF-8"));
                msg.getHeader().addField(AbstractField.parse("User-Agent: AtomPub Client API"));
                msg.setContentTransferEncoding("7bit");
                SyndContent content = (SyndContent) e.getContents().get(0);
                String value = content.getValue();
                stream.write(value.getBytes());
                stream.close();
                BodyFactory factory = new BodyFactory();
                msg.setBody(factory.textBody(composeHTML(value)));
                return msg;
            } catch (IOException ex) {
                Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            } catch (MimeException ex) {
                Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            } finally {
                try {
                    stream.close();
                } catch (IOException ex) {
                    Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, null, ex);
                    return null;
                }
            }
        }
    }

    public static String composeHTML(String value){
        try {
            String charset = EncodeDetector.detectEncode(value.getBytes("UTF-8"));
            Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, charset, charset);
            return "<html><head></head><body>" + value + "</body></html>";
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MimeMessageBuilder.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
    public static String message2String(Message m, String charset){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            m.writeTo(out);
            return out.toString(charset);
        } catch (Exception ex) {
            return null;
        }
    }

    public static byte[] message2Byte(Message m){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            m.writeTo(out);
            out.close();
            return out.toByteArray();
        } catch (Exception ex) {
            return null;
        }
    }
}
